//
//  ViewController.m
//  EFBFrameworkProject
//
//  Created by 徐 洋 on 13-8-5.
//  Copyright (c) 2013年 ADCC. All rights reserved.
//
#import <IIViewDeckController.h>
#import <PixateFreeStyle.h>

#import "EFBNotifications.h"
#import "EFBViewControllerContainer.h"
#import "EFBProperties.h"
#import "EFBUIStyle.h"

#import "AELoginViewController.h"
#import "AEIdentityManager.h"
#import "AETabbarView.h"

#define STARTBUTTON_W    44.0f
#define STARTBUTTON_h    44.0f

#define MAINTABBAR_WIDTH    84.0f
#define MAINTABBAR_HEIGHT   600.0f
#define MAINTABBAR_HEIGHT_COLLAPSE  66.0f

@interface EFBViewControllerContainer () <AETabbarViewDelegate>

@property (nonatomic, copy, readwrite) NSArray *viewControllers;
@property (nonatomic, strong) UIView *privateContainerView; /// The view hosting the child view controllers views.
@property (nonatomic, strong) AETabbarView * tabbarView;
@property (nonatomic, strong) NSDictionary * configuration;
@property (nonatomic, strong) NSLayoutConstraint * tabbarHeightConstrait;

@end

@implementation EFBViewControllerContainer

- (instancetype)initWithViewControllers:(NSArray *)viewControllers {
	NSParameterAssert ([viewControllers count] > 0);
	if ((self = [super init])) {
		self.viewControllers = [viewControllers copy];
        NSDictionary * testConfig = @{kTabbar: @{kTabbarHidden: @(NO), kTabbarItems: @[
                                                  @{kTabbarType: kTabbarTypeVCIndex, kTabbarTitle:@"机载手册", kTabbarIcon:@"tabbar-app-manual", kTabbarVCIndex:@(0)},
                                                  @{kTabbarType: kTabbarTypeVCIndex, kTabbarTitle:@"性能资料", kTabbarIcon:@"tabbar-app-perfdoc", kTabbarVCIndex:@(1)},
                                                  @{kTabbarType: kTabbarTypeVCIndex, kTabbarTitle:@"国内航图", kTabbarIcon:@"tabbar-app-chart", kTabbarVCIndex:@(2)},
                                                  @{kTabbarType: kTabbarTypeVCIndex, kTabbarTitle:@"飞行资料", kTabbarIcon:@"tabbar-app-flight-folder", kTabbarVCIndex:@(3)},
                                                  @{kTabbarType: kTabbarTypeRedirect, kTabbarTitle:@"Jepp FD", kTabbarIcon:@"tabbar-app-jeppfd", kTabbarURL:@"jepp-fd:///"}
                                                  ]
                                          }
                               }; // for debug
        
        NSString * appPath = [[NSBundle mainBundle] pathForResource:@"app" ofType:@"plist"];
        NSDictionary * appConfig = [NSDictionary dictionaryWithContentsOfFile:appPath];
        
        self.configuration = appConfig;
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(haveReceiVedBlueToothInfo:) name:@"haveReceivedBlueToothMessage" object:nil];
	}
	return self;
}

- (void)loadView {
    
	// Add  container and buttons views.
    
	UIView *rootView = [[UIView alloc] init];
	rootView.backgroundColor = [UIColor blackColor];
	rootView.opaque = YES;
    
	self.privateContainerView = [[UIView alloc] init];
	self.privateContainerView.backgroundColor = [UIColor blackColor];
	self.privateContainerView.opaque = YES;

    self.privateContainerView.frame = rootView.bounds;
	[rootView addSubview:self.privateContainerView];
    
    // Config tabbar
    
    NSDictionary * tabbarDef = self.configuration[kTabbar];
    
    BOOL tabbarHidden = tabbarDef[kTabbarHidden]?([tabbarDef[kTabbarHidden] boolValue]):YES;
    
    if (!tabbarHidden) {
        AETabbarView * tabbar = [[AETabbarView alloc] initWithConfig:tabbarDef];
        tabbar.delegate = self;
        [rootView addSubview:tabbar];
        self.tabbarView = tabbar;
        
        [tabbar setTranslatesAutoresizingMaskIntoConstraints:NO];
        self.tabbarHeightConstrait = [NSLayoutConstraint constraintWithItem:tabbar attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0f constant:TABBAR_HEIGHT];
        [rootView addConstraint:self.tabbarHeightConstrait];
        [rootView addConstraint:[NSLayoutConstraint constraintWithItem:tabbar attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:rootView attribute:NSLayoutAttributeWidth multiplier:1.0f constant:0.0f]];
        [rootView addConstraint:[NSLayoutConstraint constraintWithItem:tabbar attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:rootView attribute:NSLayoutAttributeBottom multiplier:1.0f constant:0.0f]];
        [rootView addConstraint:[NSLayoutConstraint constraintWithItem:tabbar attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:rootView attribute:NSLayoutAttributeLeading multiplier:1.0f constant:0.0f]];
    }
    
    [self.privateContainerView setTranslatesAutoresizingMaskIntoConstraints:NO];
//    self.privateContainerView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;

    [rootView addConstraint:[NSLayoutConstraint constraintWithItem:self.privateContainerView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:rootView attribute:NSLayoutAttributeTop multiplier:1.0f constant:0.0f]];
    [rootView addConstraint:[NSLayoutConstraint constraintWithItem:self.privateContainerView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:rootView attribute:NSLayoutAttributeWidth multiplier:1.0f constant:0.0f]];
    [rootView addConstraint:[NSLayoutConstraint constraintWithItem:self.privateContainerView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:rootView attribute:NSLayoutAttributeLeft multiplier:1.0f constant:0.0f]];
    
    if (tabbarHidden) {
        [rootView addConstraint:[NSLayoutConstraint constraintWithItem:self.privateContainerView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:rootView attribute:NSLayoutAttributeBottom multiplier:1.0f constant:0.0f]];
    }
    else {
        [rootView addConstraint:[NSLayoutConstraint constraintWithItem:self.privateContainerView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.tabbarView attribute:NSLayoutAttributeTop multiplier:1.0f constant:0.0f]];
    }

	self.view = rootView;
}

- (void)viewDidLoad {
	[super viewDidLoad];
	self.selectedViewController = (self.selectedViewController ?: self.viewControllers[0]);
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onSceenLocked:) name:kEFBScreenLocked object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onSceenUnlocked:) name:kEFBScreenUnlocked object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hideTabbar:) name:kEFBTabbarHidden object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showTabbar:) name:kEFBTabbarUnhidden object:nil];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    if (self.selectedViewController) {
        [self.selectedViewController viewWillAppear:animated];
    }
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    if (self.selectedViewController) {
        [self.selectedViewController viewDidAppear:animated];
    }
}

- (UIStatusBarStyle)preferredStatusBarStyle {
	return UIStatusBarStyleLightContent;
}

- (UIViewController *)childViewControllerForStatusBarStyle {
	return self.selectedViewController;
}

-(void)setSelectedViewController:(EFBBaseViewController *)selectedViewController {
	NSParameterAssert (selectedViewController);
	[self _transitionToChildViewController:selectedViewController];
	_selectedViewController = selectedViewController;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)toggleSiderPanel
{
    [self.viewDeckController toggleLeftViewAnimated:YES];
}

- (void)tabbar:(AETabbarView *)tabbar didSelectedAtIndex:(NSInteger)index
{
    self.selectedViewController = self.viewControllers[index];
}

#pragma mark Private Methods

- (void)_transitionToChildViewController:(UIViewController *)toViewController {
    
	UIViewController *fromViewController = ([self.childViewControllers count] > 0 ? self.childViewControllers[0] : nil);
	if (toViewController == fromViewController || ![self isViewLoaded]) {
		return;
	}
    
	UIView *toView = toViewController.view;
	[toView setTranslatesAutoresizingMaskIntoConstraints:YES];
	toView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
	toView.frame = self.privateContainerView.bounds;
    
	[fromViewController willMoveToParentViewController:nil];
	[fromViewController.view removeFromSuperview];
	[fromViewController removeFromParentViewController];
	[self addChildViewController:toViewController];
	[toViewController didMoveToParentViewController:self];
	[self.privateContainerView addSubview:toView];
}

- (void)onSceenLocked:(NSNotification *)note
{
    [self hideTabbar:nil];
}

- (void)onSceenUnlocked:(NSNotification *)note
{
    [self showTabbar:nil];
}

- (void)hideTabbar:(NSNotification *)note
{
    [self.tabbarHeightConstrait setConstant:0.0f];
    self.tabbarView.hidden = YES;
}

- (void)showTabbar:(NSNotification *)note
{
    [self.tabbarHeightConstrait setConstant:TABBAR_HEIGHT];
    self.tabbarView.hidden = NO;
}


- (void)toggleUpdaterPanelAtIndex:(NSInteger)index
{
    BOOL isVaild = self.viewControllers.count >= index ? YES : NO;
    if (isVaild) {
        self.selectedViewController = self.viewControllers[index];
    }
}

- (void)haveReceiVedBlueToothInfo:(NSNotification *)notice
{
    int number = [[notice.object objectForKey:@"number"] intValue];
    [self toggleUpdaterPanelAtIndex:number];
    if (number == 1) {
        // 手册
        [[NSNotificationCenter defaultCenter] postNotificationName:@"hasBeenReceivedManual" object:nil userInfo:notice.userInfo];
    } else if (number == 2){
        // 性能
        [[NSNotificationCenter defaultCenter] postNotificationName:@"hasBeenReceivedPerformance" object:nil userInfo:notice.userInfo];
    }else if (number == 3){
        // 航图
        NSString *blueSiZiMa = [notice.userInfo objectForKey:@"blueSiZiMa"];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"changeVersionChartByblueT" object:notice.userInfo];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"selectedAirportOfChartsChanged" object:blueSiZiMa];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"openPDF" object:notice.userInfo userInfo:nil];
    }
    
}
@end
